/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xml.judge;

import beans.Judge;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.digester3.Digester;
import static org.apache.commons.digester3.binder.DigesterLoader.newLoader;
import org.apache.commons.digester3.xmlrules.FromXmlRulesModule;
import org.xml.sax.SAXException;

/**
 *
 * @author heinen
 */
public class JudgeReader {

    List<Judge> judges;

    public JudgeReader() {
        judges = new ArrayList<>();
    }
    
    public void addJudge(Judge judge){
        this.judges.add(judge);
    }
    
    public List<Judge> getAllJudges(){
        
        final String rulesfileName = "src/xml/judge/JudgeRules.xml";
        String datafileName = "src/xml/judge/judges.xml";
        Digester d = newLoader(new FromXmlRulesModule() {
            @Override
            protected void loadRules() {
                loadXMLRules(new File(rulesfileName));
            }
        }).newDigester();

        //Beers beers = new Beers();
        d.push(this);

        try {
            File srcFile = new File(datafileName);
            d.parse(srcFile);
        } catch (IOException ioe) {
            System.out.println("Error reading input file:" + ioe.getMessage());
            System.exit(-1);
        } catch (SAXException se) {
            System.out.println("Error parsing input file:" + se.getMessage());
            System.exit(-1);
        }
        
        return judges;
        
    }
    
    public Judge getJudgeByName(String name){
        List<Judge> allJudges = getAllJudges();
        for(Judge j : allJudges){
            if(j.getName().equalsIgnoreCase(name)){
                return j;
            }
        }
        return null;
    }
    
    public Judge getJudgeById(Long id){
        List<Judge> allJudges = getAllJudges();
        for(Judge j : allJudges){
            if(j.getId().equals(id)){
                return j;
            }
        }
        return null;
    }
    
    public Judge getJudgeByBJCPId(String bjcpId){
        List<Judge> allJudges = getAllJudges();
        for(Judge j : allJudges){
            if(j.getBjcpId().equals(bjcpId)){
                return j;
            }
        }
        return null;
    }
    
}
